package org.my.workflow;

import java.net.URL;
import java.util.Collection;

import org.my.workflow.element.StepElement;
import org.my.workflow.element.WorkflowElement;
import org.my.workflow.element.XMLUtils;
import org.my.workflow.persistence.MemoryWorkflowPersistence;
import org.w3c.dom.Document;

/**
 * @author <a href="mailto:yang_y@sysnet.com.cn">Young Yang</a>
 */
public class WorkflowConfig {

    private WorkflowElement workflowElement;

    private URL configURL;

    private WorkflowPersistence wfPersistence;

    private WorkflowConfig(URL url) {
        this.configURL = url;
        initialize();
    }

    private void initialize() {
        try {
            Document document = XMLUtils.loadDocument(configURL);
            workflowElement = new WorkflowElement();
            workflowElement.processXML(document.getDocumentElement());
        }
        catch (Exception e) {
            throw new WorkflowException("Workflow initialize failed.", e);
        }
    }

    public static WorkflowConfig loadConfiguration(URL configURL) {
        return new WorkflowConfig(configURL);
    }

    public URL getConfigURL() {
        return configURL;
    }

    public Workflow newWorkflow(String owner, Payload payload) {
        return new Workflow(this, owner, payload);
    }

    public Workflow loadWorkflow(String id) {
        //TODO: loadWorflow from persistence
        return null;
    }

    public WorkflowPersistence getPersistence() {
        if(wfPersistence == null) {
            // default persistence
            wfPersistence = new MemoryWorkflowPersistence();
        }
        return wfPersistence;
    }


    public WorkflowElement getWorkflowElement() {
        return workflowElement;
    }

    public Collection<StepElement> getSteps() {
        return workflowElement.getStepElements();
    }

    public StepElement getStep(String stepId) {
        return workflowElement.getStepElementById(stepId);
    }

    public static void main(String[] args) throws Exception{

    }
}
